import Vue from 'vue'
import router from './router'
import store from './store'
import { axios } from '@/utils/request'
import { api } from '@/api/common'
import { notification } from 'ant-design-vue'
import { ACCESS_TOKEN, TENANTID } from '@/store/mutation-types'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['login', 'register', 'registerResult', 'changePwd', 'bindWechat'] // no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  if (Vue.ls.get(ACCESS_TOKEN)) {
    /* has token */
    if (to.path === '/user/login') {
      next({ path: '/workplace' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) {
        store.dispatch('GetInfo')
          .then(() => { store.dispatch('GetBasicsInfo') })
          .then(() => {
            // 调用 vuex 的 从后端获取用户的路由菜单，动态添加可访问路由表
            store.dispatch('GenerateRoutes').then(() => {
              // 把已获取到的路由菜单加入到路由表中
              // console.log(JSON.parse(JSON.stringify(store.getters.addRouters)));
              router.addRoutes(store.getters.addRouters)
              const redirect = decodeURIComponent(from.query.redirect || to.path)
              if (to.path === redirect) {
                // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                next({ ...to, replace: true })
              } else {
                // 跳转到目的路由
                next({ path: redirect })
              }
            })
          })
          .catch(() => {
            console.log('请求用户信息失败');
            store.dispatch('Logout').then(() => {
              next({ path: '/user/login', query: { redirect: '/' } })
            })
          })
      } else {
        next()
      }
    }
  } else {
    if (to.fullPath.split('?').length > 1) {
      var str = to.fullPath.split('?')[1].split('&')
      var searchObj = {}
      for (var item of str) {
        var itemArr = item.split('=')
        searchObj[itemArr[0]] = itemArr[1]
      }
      if (searchObj.code) {
        axios({
          url: api.wechatLogin,
          method: 'get',
          params: {
            code: searchObj.code,
            state: searchObj.state
          }
        }).then(res => {
          if (res.code === 0 && res.data.isBind) {
            Vue.ls.set(ACCESS_TOKEN, res.data.token, 12 * 60 * 60 * 1000)
            store.commit('SET_TOKEN', res.data.token)
            next({ path: '/' })
            NProgress.done()
          } else if (res.code === 0 && !res.data.isBind) {
            next({ path: '/user/bindWechat', query: { redirect: '/', socialUserId: res.data.socialUserId } })
            NProgress.done()
          }
        })
      } else {
        if (whiteList.includes(to.name)) {
          // 在免登录白名单，直接进入
          next()
        } else {
          if (to.fullPath) { }
          next({ path: '/user/login', query: { redirect: '/' } })
          NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
        }
      }
    } else {
      if (whiteList.includes(to.name)) {
        // 在免登录白名单，直接进入
        next()
      } else {
        if (to.fullPath) { }
        next({ path: '/user/login', query: { redirect: '/' } })
        NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
      }
    }
  }
})

router.afterEach(() => {
  if (store.getters.sysConfig && store.getters.sysConfig.sysTitle) {
    window.document.title = store.getters.sysConfig.sysTitle
  }
  if (store.getters.sysConfig && store.getters.sysConfig.logoUrl && store.getters.sysConfig.logoUrl.imagePathSmall) {
    document.getElementById('iconLogo').href = store.getters.sysConfig.logoUrl.imagePathSmall
  }
  NProgress.done() // finish progress bar
})
